 function [t  ] =     generateSelfPlotCVS(type,numPoints , repeatEach )
% numpoints is the number of intervals on the x axis and repeatEach is the
% number of times the experiment has to be performd for each outlier ratio

tic

close all
   fclose all
startp=0;
endp=1;
t=startp:((endp-startp)/(numPoints-1)):endp;
differFocal=7;
deviationCenter=20;
skew=0;
aspect=1.1;
numBadFocs=2;
numPs=5;
numparams=3;
noisestd=0;
numdifferentframes=0;
  myxlabel='outlier ratio';
if(strcmp(type,'synthetic')==1 || strcmp(type,'degeneracy')==1 || strcmp(type,'fdiff')==1)
    myxlabel='outlier ratio';
    width=1024;
    height =768;
end
if( strcmp(type,'degeneracy')==1)
    startp=0;
    endp=0.1;
    t=startp:((endp-startp)/(numPoints-1)):endp;
end
if( strcmp(type,'fdiff')==1)
    myxlabel='focal length deviation';
    startp=100;
    endp=width;
    t=startp:((endp-startp)/(numPoints-1)):endp;
    numdifferentframes=1;
end
if( strcmp(type,'fbad')==1 || strcmp(type,'fbaddiff')==1  || strcmp(type,'wadham')==1   || strcmp(type,'rathaus')==1  || strcmp(type,'fountainp11')==1)
    myxlabel='number of noisy fundamental matrices';
    startp=0;
    endp=16;
     t=startp:2:(endp-2);
    numPoints=size(t,2);
     numdifferentframes=0;
end
if( strcmp(type,'ocdeviate')==1)
    myxlabel='optical center deviation';
    startp=0;
    endp=300;
    t=startp:50:endp;
    numdifferentframes=1;
end
if( strcmp(type,'timingf')==1 )
    myxlabel='number frames';
    startp=4;
    endp=9;
     t=startp:1:endp;
    numPoints=size(t,2);
     numdifferentframes=0;
end



% create a directory
mtime=clock;
[curdirname]=findUniqueDirname('datafilesd', ['subdir_m_' num2str(mtime(1,2)) '_d_' num2str(mtime(1,3)) '_h_' num2str(mtime(1,4)) '_s_' num2str(ceil(mtime(1,5))) '_v']);
mkdir([curdirname '/extras']);
mkdir([curdirname '/code']);
fid2 = fopen([curdirname '/command.txt'  ], 'wt');
fprintf(fid2,' type: %s \n numPoints %f \n repeatEach %f \n  ',type,numPoints , repeatEach);
fclose(fid2);

% algorithms
%AlgNames={'selfCalibUnrobust','geometricSelfCalib','findRobustWeightsperfinal','puttestshere3'};
AlgNames={'puttestshere3','selfCalibmultistart','selfCalibUnrobust','geometricSelfCalib','findRobustWeightsperfinal'};
numalgs=size(AlgNames,2);

%initializing outputs
% number of times to repeat experiments per error ratio X number of data
% points X number of algorithms
means_F=zeros(numPoints,numalgs, repeatEach);
means_XY=zeros(numPoints,numalgs, repeatEach);
timeCPU=zeros(numPoints,numalgs, repeatEach);
resultsPerE_f=zeros(numalgs, repeatEach);
resultsPerE_ocx=zeros(numalgs, repeatEach);

numIt=0;
totalIT=numPoints*repeatEach;
for i=1:numPoints
    resultsPerE_f=resultsPerE_f*0;
    resultsPerE_ocx=resultsPerE_ocx*0;
    
    for j=1:repeatEach
        
        
        numIt=numIt+1;
        
        clear F ks P corrs
        if(strcmp(type,'synthetic')==1)
        %    [F, ks,~ , ~,corrs,~,~,~,~,~,~ ] = generateF(differFocal*abs(randn()), skew*abs(randn()), abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,t(1,i),numBadFocs ,1024,768,noisestd );
          [F, ks,~ , ~,corrs,~,~,~,~,~,~ ] = generateF(0, 0, abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,t(1,i),numBadFocs ,1024,768,noisestd );
        elseif(strcmp(type,'ocdeviate')==1)
                [F, ks,~ , ~,corrs,~,~,~,~,width,height] = generateF(0, 0, abs(aspect+(0.2*randn())),t(1,i),1,numPs,0,0 ,1024,768,1 );
     elseif(strcmp(type,'timingf')==1)
                [F, ks,~ , ~,corrs,~,~,~,~,width,height] = generateFBADP(0, 0, abs(aspect+(0.2*randn())),rand*deviationCenter,1,t(1,i),0.5,1 ,1024,768,noisestd );
   
        elseif(strcmp(type,'degeneracy')==1)
            [F, ks,~ , ~,corrs ] = generateFtwoangel(differFocal, skew, aspect,deviationCenter,1,numPs,0,0 ,width,height,t(1,i)  );
       elseif(strcmp(type,'fbad')==1)
            [F, ks,~ , ~,corrs,~,~,~,~,width,height ] = generateF(0, 0, abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,0.95,t(1,i) ,1024,768,noisestd );
         elseif(strcmp(type,'fbaddiff')==1)
             [Fb, ksb,~ , ~,corrsb,~,~,~,~,~,~ ] = generateF(0, 0, abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,0,0 ,1024*2,768*2,noisestd );
            [F, ks,~ , ~,corrs,~,~,~,~,width,height ] = generateF(0, 0, abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,0,0 ,1024,768,noisestd );    
             for qq=1:t(1,i)
                 F{1,qq}=Fb{1,qq};
             end  
  
        elseif(strcmp(type,'fdiff')==1)
            [F, ks,~ , ~,corrs,~,~,~,~,width,height ] = generateF(t(1,i), 0,  abs(aspect+(0.2*randn())),rand*deviationCenter,1,numPs,0,0 ,1024,768,noisestd ,numdifferentframes );
 
        else
       %     [corrs, IMS, ~,ks, F] = readCorrsOxford(type, 0.5,t(1,i),0,0);
       [ F,corrs,ks,height,width, FFORMATTED,IMS,corrsFormatted] = generateFImages(type,0,t(1,i),0 );
            [height,width,~]=size(IMS{1,1});
        end
        
        mydisplay(['*** i is ' num2str(i) ' and j is ' num2str(j) ' iteration ' num2str(numIt) ' out of ' num2str(totalIT) ],curdirname);
        mydisplay([' input fund matrix is ' type ' with focal length: ' num2str(ks{1}(1,1)) ' OX: ' num2str(ks{1}(1,3)) ' OY : ' num2str(ks{1}(2,3)) ' total frames: ' num2str(numPs) ],curdirname);
        
        addKs(ks,width, height, i,j, t(1,i),type,curdirname,'inputs.csv');
        save([curdirname '/extras/genmat_i_' num2str(i) '_j_' num2str(j) '.mat'], 'F', 'ks','corrs');
        for k=1:numalgs
            
            tStart=tic;
             fh=str2func(AlgNames{k});
             TKK=zeros(3,3);
            [TKK]=fh(F,width,height,numparams,corrs);
            
            save([curdirname '/extras/genmat_i_' num2str(i) '_j_' num2str(j) '_algsolution_' AlgNames{k} '.mat'], 'TKK','-ASCII');
            
            answerf=[ TKK(1,1) TKK(2,2)];
            loca=[ TKK(1,3) TKK(2,3)];
            tElapsed = toc(tStart);
            
            timeCPU(i,k,j)=tElapsed;
            
            [ means_F(i,k,j),  means_XY(i,k,j)  ] = calcSelfCalibError(answerf, loca,ks,numdifferentframes);
            addanswers(answerf, loca(1,1),loca(1,2),tElapsed,width, height, i,j, t(1,i),type,curdirname,[AlgNames{k} 'answers.csv'] );
            addErrors(means_F(i,k,j), means_XY(i,k,j) ,tElapsed,width, height, i,j, t(1,i),type,curdirname,[AlgNames{k} 'errors.csv'])
            
            mydisplay([' algorithm ' AlgNames{k} ' had focal error ' num2str(means_F(i,k,j)) ' and OC error ' num2str( means_XY(i,k,j)) ' time: ' num2str( timeCPU(i,k,j))],curdirname);
            
            
            resultsPerE_f(k,j)=means_F(i,k,j) ;
            resultsPerE_ocx(k,j)= means_XY(i,k,j)  ;
        end
        
        
    end
    
    curmeans=mean(resultsPerE_f,2);
    [B,IX] = sort(curmeans);
    for k=1:numalgs
        
       mydisplay(['Winner number ' num2str(k) ' error: ' num2str(t(1,i)) ' ALGORITHM : '  AlgNames{IX(k)} ' had mean errors: f=' num2str(mean(resultsPerE_f(IX(k),:),2)) '  OC= ' num2str(mean(resultsPerE_ocx(IX(k),:),2)) ],curdirname);
    end
    
    
end



summarizeandWriteGraphData(means_F,t,AlgNames,'focal length error',curdirname );
summarizeandWriteGraphData(means_XY,t,AlgNames,'optical center error',curdirname );
summarizeandWriteGraphData(timeCPU,t,AlgNames,'time',curdirname );

save([curdirname '/allworkspace.txt '],  '-ASCII');

mydisplay([ ' printed in dir : ' curdirname],curdirname);


ReadCVSplotSelective([curdirname '/' 'focal length error' 'mean.csv'  ],[curdirname '/' 'focal length error' 'variance.csv'  ],myxlabel,'focal length error',1);
matlab2tikz( [curdirname '/' 'focal length error' 'mean.tikz'  ], 'height', '\figureheight', 'width', '\figurewidth' );
close all
ReadCVSplotSelective([curdirname '/' 'optical center error' 'mean.csv'  ],[curdirname '/' 'optical center error' 'variance.csv'  ],myxlabel,'optical center error',1);
matlab2tikz( [curdirname '/' 'optical center error' 'mean.tikz'  ], 'height', '\figureheight', 'width', '\figurewidth' );

ReadCVSplotSelective([curdirname '/' 'timemean.csv'  ],[curdirname '/' 'timevariance.csv'  ],myxlabel,'computation time',1);
matlab2tikz( [curdirname '/' 'timemean.tikz'  ], 'height', '\figureheight', 'width', '\figurewidth' );


copyfile('*.m',[curdirname '\code']);
save([curdirname '/workspace.mat ']);

toc
end

function []= writeGraphData(stuffdata, t, label,dirname,algz,pnumalgs,pnumPoints)
fid = fopen([dirname '/' label '.csv'  ], 'wt');


fprintf(fid,' error ratio, ');
for k=1:pnumalgs
    fprintf(fid,[algz{k} ]);
        if(k~=pnumalgs)
               fprintf(fid,[ ' , ']);
        end
    
end
fprintf(fid,' \n ');

for i=1:pnumPoints
    fprintf(fid, [num2str(t(1,i)) ' , ']);
    for k=1:pnumalgs
        
        fprintf(fid, [num2str(stuffdata(i,k)) ]);
        
        if(k~=pnumalgs)
             fprintf(fid, [ ' , ']);
        end
    end
    fprintf(fid,' \n ');
end


fclose(fid);
end


function []=summarizeandWriteGraphData(datamatrix,xaxis,algz,label,dirname )

meanz=zeros(size(xaxis,2),size(algz,2));
variancez=zeros(size(xaxis,2),size(algz,2));
medianz=zeros(size(xaxis,2),size(algz,2));

pnumalgs=size(algz,2);
pnumPoints=size(xaxis,2);

for i=1:pnumPoints
    
    for k=1:pnumalgs
        
        meanz(i,k)=  mean(datamatrix(i,k,:))    ;
        variancez(i,k)=var(datamatrix(i,k,:))    ;
        medianz(i,k)= median(datamatrix(i,k,:))    ;
    end
    
end

writeGraphData( meanz, xaxis, [label 'mean'],dirname ,algz,pnumalgs,pnumPoints);
writeGraphData( variancez, xaxis, [label 'variance'],dirname ,algz,pnumalgs,pnumPoints);
writeGraphData( medianz, xaxis, [label 'medianz'],dirname ,algz,pnumalgs,pnumPoints);
mydisplay(['written to directory: ' dirname],dirname);
end

function []= addKs(ksp,widthp, heightp, ip,jp, tp,typep,curdirnamep,fname)

fname=[curdirnamep '/' fname];
fid = fopen(fname, 'at');
if(ip==1 && jp==1)
    fprintf(fid,' i , j, error ratio, width, height, seguence name,');
    for i=1:size(ksp,2)
        frame=['frame_' num2str(i)];
        fprintf(fid, [frame 'focal length1 ,' frame 'focal length2 ,' frame 'x center ,' frame 'y center ,' frame 'skew ,']);
    end
    fprintf(fid, '\n');
end

fprintf(fid,[num2str(ip) ' , ' num2str(jp) ' , ' num2str(tp) ' , ' num2str(widthp) ' , ' num2str(heightp) ' , '  typep ' , '  ]);
for i=1:size(ksp,2)
    fprintf(fid, [ksp{i}(1,1) ' , ' ksp{i}(2,2) ' , ' ksp{i}(1,3) ' , ' ksp{i}(2,3) ' , ' ksp{i}(1,2)  ' , ']);
end
fprintf(fid, '\n');

fclose(fid);
end

function []=mydisplay(text,dname)
disp(text);
fid3 = fopen([dname '/display.txt'  ], 'at');
fprintf(fid3,[text '\n']);
fclose(fid3);
end

function []= addanswers(fcl, ocx,ocy,ttim,widthp, heightp, ip,jp, tp,typep,curdirnamep,fname)

fname=[curdirnamep '/' fname];
fid = fopen(fname, 'at');
if(ip==1 && jp==1)
    fprintf(fid,' i , j, error ratio, width, height, seguence name, focal answer , x center, y center, time \n');
end



fprintf(fid,[num2str(ip) ' , ' num2str(jp) ' , ' num2str(tp) ' , ' num2str(widthp) ' , ' num2str(heightp) ' , '  typep ' , '   num2str(fcl) ' , '  num2str(ocx) ' , '  num2str(ocy) ' , ' num2str(ttim) ' \n ']);
fclose(fid);
end



function []= addErrors(fError, ocxError,ttim,widthp, heightp, ip,jp, tp,typep,curdirnamep,fname)

fname=[curdirnamep '/' fname];
fid = fopen(fname, 'at');
if(ip==1 && jp==1)
    fprintf(fid,' i , j, error ratio, width, height, seguence name, focal Length error , OC error , time \n');
end



fprintf(fid,[num2str(ip) ' , ' num2str(jp) ' , ' num2str(tp) ' , ' num2str(widthp) ' , ' num2str(heightp) ' , '  typep ' , '   num2str(fError) ' , '  num2str(ocxError) ' , ' num2str(ttim) ' \n ']);
fclose(fid);
end